<template>
  <a-modal
    :width="850"
    style="top: 0"
    v-model="visible"
    :title="`${text}题目`"
    :maskClosable="false"
    :bodyStyle="{padding: '10px'}"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <a-button :disabled="mode === 'detail'" key="submit" type="primary" :loading="loading" @click="handleSubmit">{{ text }}</a-button>
      <a-button key="back" @click="handleCancel">取消</a-button>
    </template>

    <a-form-model :model="postForm" :rules="rules" ref="ruleForm">

      <a-row>
        <a-col :span="12">
          <a-form-model-item
            label="题目类型"
            prop="questionTypeSel"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-select
              :disabled="mode === 'edit'"
              v-model="postForm.questionTypeSel"
              @change="handleTypeChange"
              :getPopupContainer="triggerNode => triggerNode.parentNode"
            >
              <a-select-option v-for="item in quTypeSel" :key="item.value">{{ item.label }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <!--<a-col :span="12">-->
          <!--<a-form-model-item-->
            <!--label="题目分类"-->
            <!--prop="questionType"-->
            <!--:labelCol="labelCol"-->
            <!--:wrapperCol="wrapperCol"-->
          <!--&gt;-->
            <!--<a-select v-model="postForm.questionType" :getPopupContainer="triggerNode => triggerNode.parentNode">-->
              <!--<a-select-option v-for="item in quTypes" :key="item.value">{{ item.label }}</a-select-option>-->
            <!--</a-select>-->
          <!--</a-form-model-item>-->
        <!--</a-col>-->
        <a-col :span="12">
          <a-form-model-item
            label="题目分数"
            prop="questionScore"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input-number style="width: 100%" v-model="postForm.questionScore" :min="1" :max="100"/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col>
          <a-form-model-item
            label="归属题库"
            prop="examIds"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <div v-if="visible">
              <ItemBankSelect mode="multiple" v-model="postForm.examIds"/>
            </div>
          </a-form-model-item>
        </a-col>

      </a-row>

      <a-row>
        <a-col :span="24">
          <a-form-model-item
            label="题目内容"
            prop="questionTitle"
            :labelCol="labelColItem"
            :wrapperCol="wrapperColItem"
          >
            <a-textarea :rows="3" v-model="postForm.questionTitle"/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!--<a-row>-->
        <!--<a-col :span="24">-->
          <!--<a-form-model-item-->
            <!--label="题目图片"-->
            <!--:labelCol="labelColItem"-->
            <!--:wrapperCol="wrapperColItem"-->
            <!--style="margin-bottom: 5px"-->
          <!--&gt;-->
            <!--<div v-if="visible">-->
              <!--<ImageUpload-->
                <!--ref="questionImage"-->
                <!--:image="{ id: postForm.id, imageName: postForm.imageName, imageUrl: postForm.imageUrl }"-->
              <!--/>-->
            <!--</div>-->
          <!--</a-form-model-item>-->
        <!--</a-col>-->
      <!--</a-row>-->

      <a-row>
        <a-col :span="24">
          <div v-if="postForm.questionTypeSel !== 3">
            <a-form-model-item
              label="客观题答案"
              prop="questionAnswer"
              :labelCol="labelColItem"
              :wrapperCol="wrapperColItem"
            >
              <a-select
                v-model="postForm.questionAnswer"
                :mode="postForm.questionTypeSel === 1 ? 'multiple' : 'default'"
                :getPopupContainer="triggerNode => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="item in selectCode"
                  :key="item.value"
                  :disabled="!postForm.questionOptionList.map(({ code }) => code).includes(item.value)"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </div>
          <div v-else>
            <a-form-model-item
              label="主观题答案"
              prop="questionAnswerReply"
              :labelCol="labelColItem"
              :wrapperCol="wrapperColItem"
            >
              <a-textarea :rows="4" v-model="postForm.questionAnswerReply"/>
            </a-form-model-item>
          </div>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <a-form-model-item
            label="题目解析"
            :labelCol="labelColItem"
            :wrapperCol="wrapperColItem"
          >
            <a-textarea :rows="4" v-model="postForm.analysis"/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <div v-if="postForm.questionTypeSel !== 3" class="filter-container">

        <a-button
          plain
          icon="plus"
          size="small"
          type="primary"
          class="filter-item"
          @click="addItem"
          :disabled="postForm.questionOptionList.length === selectCode.length || postForm.questionTypeSel === 2"
        >
          添加
        </a-button>

        <a-table
          bordered
          rowKey="key"
          style="width: 100%;"
          :columns="columns"
          :pagination="false"
          :dataSource="postForm.questionOptionList"
        >
          <template slot="code" slot-scope="text, record">
            <a-input disabled v-model="record['code']" />
          </template>

          <!--<template slot="imageUrl" slot-scope="text, record, index">-->
            <!--<div v-if="visible">-->
              <!--<ImageUpload :ref="`optionImage${index}`" :image="record"/>-->
            <!--</div>-->
          <!--</template>-->

          <template slot="content" slot-scope="text, record">
            <a-textarea :rows="3" v-model="record['content']"/>
          </template>

          <template slot="action" slot-scope="text, record, index">
            <a-button
              type="danger"
              shape="circle"
              icon="delete"
              @click="removeItem(index, record)"
              :disabled="postForm.questionOptionList.length > index + 1 || postForm.questionOptionList.length <= 2 || mode === 'edit'"
            ></a-button>

          </template>

        </a-table>

      </div>

    </a-form-model>

  </a-modal>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import mappingConfig from '@/config/mappingConfig'
import ImageUpload from '../coms/SingleImageUpload'
import ItemBankSelect from '@/hzjComponents/select/ItemBankSelect'

import validateRules from '@/utils/validate'
import imageService from '@/service/fileUpload'
import questionService from '@/service/exam/questionManage'

const quTypeSel = Object.entries(mappingConfig.exam.question.typeSel)
  .map(([k, v]) => ({ value: Number.parseInt(k, 10), label: v }))

const quTypes = Object.entries(mappingConfig.exam.question.type)
  .map(([k, v]) => ({ value: Number.parseInt(k, 10), label: v }))

const selectCode = Object.values(mappingConfig.exam.question.code).map(m => ({ value: m, label: m }))

const codeMap = { ...mappingConfig.exam.question.code }

// 用户信息
const loginUserInfo = Vue.ls.get('loginUserInfo') || {}

const addCommonInfo = {
  status: 0,
  isDeleted: 0,
  createDept: loginUserInfo.id,
  createUser: loginUserInfo.deptId,
  createTime: moment().format('YYYY-MM-DD HH:mm:ss')
}

const editCommonInfo = {
  updateUser: loginUserInfo.deptId,
  updateTime: moment().format('YYYY-MM-DD HH:mm:ss')
}

const columns = [
  {
    width: 90,
    align: 'center',
    title: '答案编码',
    dataIndex: 'code',
    scopedSlots: { customRender: 'code' }
  },
//  {
//    width: 90,
//    align: 'center',
//    title: '答案图片',
//    dataIndex: 'imageUrl',
//    scopedSlots: { customRender: 'imageUrl' }
//  },
  {
    align: 'center',
    title: '答案内容',
    dataIndex: 'content',
    scopedSlots: { customRender: 'content' }
  },
  {
    width: 80,
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    ImageUpload,
    ItemBankSelect
  },
  data () {
    const validateExamIds = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请至少选择一个题库'))
      } else {
        callback()
      }
    }
    const validateQuestionAnswer = (rule, value, callback) => {
      const { questionAnswer } = this.postForm
      const { questionTypeSel } = this.postForm
      switch (questionTypeSel) {
        case 0:
          if (!value) {
            callback(new Error('单选题至少选择一个答案'))
          } else {
            callback()
          }
          break
        case 1:
          if (!value) {
            callback(new Error('多选题至少选择两个答案'))
          } else if (Array.isArray(questionAnswer) && questionAnswer.length === 1) {
            callback(new Error('多选题至少选择两个答案'))
          } else {
            callback()
          }
          break
        case 2:
          if (!value) {
            callback(new Error('判断题请选择一个答案'))
          } else {
            callback()
          }
      }
    }
    return {
      text: '',
      mode: 'add',

      visible: false,
      loading: false,

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelColItem: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperColItem: {
        xs: { span: 24 },
        sm: { span: 20 }
      },

      columns,
      quTypes,
      quTypeSel,
      selectCode,

      postForm: {
        questionTypeSel: '', // 题目类型（0：单选题 1多选题 2 判断题 3 简答题）
        questionType: 0, // 题目类型  0：岗位职责   1：问病荐药  2：综合练习
        examIds: undefined, // 题库ids
        questionTitle: '', // 题目描述
        imageName: '', // 题目图片名称
        imageUrl: '', // 题目图片url
        questionAnswer: '', // 客观题答案
        questionAnswerReply: '', // 主观题参考答案
        questionScore: 1, // 题目分数
        analysis: '', // 题目解析
        questionOptionList: [] // 题目选项
      },

      rules: {
        questionTypeSel: [{ type: 'number', required: true, message: '请选择题目类型', trigger: 'change' }],
//        questionType: [{ type: 'number', required: true, message: '请选择题目分类', trigger: 'change' }],
        examIds: [{ type: 'string', validator: validateExamIds, trigger: 'change' }],
        questionScore: [{ type: 'number', required: true, message: '题目分数不能为空', trigger: 'bluer' }],
        questionTitle: [{ type: 'string', required: true, message: '题目内容不能为空', trigger: 'blur' }],
        questionAnswer: [{ type: 'string', validator: validateQuestionAnswer, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'postForm.questionTypeSel': function (val) {
      const { questionAnswer } = this.postForm
      if (val === 0) {
        if (Array.isArray(questionAnswer) && questionAnswer.length > 0) {
          this.postForm.questionAnswer = questionAnswer[0]
        }
      } else if (val === 1 && this.mode === 'add') {
        if (questionAnswer && !Array.isArray(questionAnswer)) {
          this.postForm.questionAnswer = [questionAnswer]
        } else {
          this.postForm.questionAnswer = []
        }
      } else if (val === 2) {
        if (Array.isArray(questionAnswer) && questionAnswer.length > 0) {
          if (questionAnswer[0] === 'B') {
            this.postForm.questionAnswer = 'B'
          } else {
            this.postForm.questionAnswer = 'A'
          }
        }
      } else if (val === 3) {
        this.postForm.questionAnswer = ''
      }
    },
    'postForm.examIds': function (val) {
      if (this.$refs.ruleForm) {
        if (!val) {
          this.$refs.ruleForm.validateField('examIds')
        } else {
          this.$refs.ruleForm.clearValidate('examIds')
        }
      }
    }
  },
  methods: {
    handleCancel () {
      this.resetFields()
      this.visible = false
    },
    handleTypeChange (v) {
      this.postForm.questionOptionList = []
      if (v === 2) {
        this.postForm.questionOptionList.push({ key: 0, code: 'A', content: '正确', imageUrl: '', imageName: '' })
        this.postForm.questionOptionList.push({ key: 1, code: 'B', content: '错误', imageUrl: '', imageName: '' })
      }
      if (v === 0 || v === 1) {
        this.postForm.questionOptionList.push({ key: 0, code: 'A', content: '', imageUrl: '', imageName: '' })
        this.postForm.questionOptionList.push({ key: 1, code: 'B', content: '', imageUrl: '', imageName: '' })
        this.postForm.questionOptionList.push({ key: 2, code: 'C', content: '', imageUrl: '', imageName: '' })
        this.postForm.questionOptionList.push({ key: 3, code: 'D', content: '', imageUrl: '', imageName: '' })
      }
    },
    addItem () {
      const len = this.postForm.questionOptionList.length
      this.postForm.questionOptionList.push({ key: len, code: codeMap[len], content: '', imageUrl: '', imageName: '' })
    },
    removeItem (index, record) {
      this.postForm.questionOptionList.splice(index, 1)
      if (this.mode === 'edit') {
      // 后台删除题目对应选项
        console.log(record)
      }
    },
    showAdd () {
      this.text = '新增'
      this.mode = 'add'
      this.visible = true
    },
    // 回显
    showEdit (record) {
      this.text = '修改'
      this.mode = 'edit'
      const { question, questionOptionList, examIds } = record || {}
      const { id, questionTypeSel, questionType, imageName, imageUrl } = question
      const { questionTitle, questionAnswer, questionAnswerReply, questionScore, analysis } = question
      this.postForm = {
        id,
        questionTypeSel,
        questionType,
        examIds,
        questionTitle,
        questionAnswerReply,
        questionScore,
        analysis,
        imageName,
        imageUrl,
        questionAnswer: questionTypeSel === 1 ? questionAnswer.split(',') : questionAnswer,
        questionOptionList: questionOptionList.map(({ id, code, imageName, imageUrl, content }, inx) =>
          ({ key: inx, id, code, imageName, imageUrl, content })).sort((a, b) => {
          if (a.code > b.code) { return 1 } else if (a.code < b.code) { return -1 }
          return 0
        })
      }
      this.visible = true
    },
    async save () {
      let { imageName, imageUrl } = this.postForm
      const { questionTypeSel, questionType, examIds, questionTitle } = this.postForm
      const { questionAnswer, questionAnswerReply, questionScore, analysis, questionOptionList } = this.postForm
      // 验证客观题选项内容不能为空
      for (let i = 0; i < questionOptionList.length; i += 1) {
        if (!questionOptionList[i].content.trim()) {
          this.$message.info(`第${i + 1}行答案内容不能为空`)
          return
        }
      }
      // 验证主观题答案不能为空
      if (questionTypeSel === 3 && !questionAnswerReply) {
        this.$message.info('主观题答案不能为空')
        return
      }
      this.loading = true
      // 验证题目是否上传了图片
//      const questionImages = this.$refs.questionImage.getFileList()
//      if (questionImages.length > 0) {
//        // 题目图片类型、大小验证
//        const { flag, msg_ } = validateRules.validateImgTypeAndSize(questionImages)
//        if (!flag) {
//          this.$message.info(msg_)
//          this.loading = false
//          return
//        }
//        // 上传题目图片
//        const formData = new FormData()
//        questionImages.forEach(file => {
//          formData.append('file', file)
//        })
//        const { code, data, msg } = await imageService.uploadVideo(formData) || {}
//        if (code !== 200) {
//          this.$message.error(msg || '上传题目图片失败')
//          this.loading = false
//          return
//        }
//        const { fileName, fileUrl } = data
//        imageName = fileName
//        imageUrl = fileUrl
//      }
//      if (questionOptionList.length > 0) {
//        // 验证题目选项是否上传了图片
//        for (let i = 0; i < questionOptionList.length; i += 1) {
//          const optionImages = this.$refs['optionImage' + i].getFileList()
//          if (optionImages.length > 0) {
//            // 题目图片类型、大小验证
//            const { flag, msg_ } = validateRules.validateImgTypeAndSize(optionImages)
//            if (!flag) {
//              this.$message.info(msg_)
//              this.loading = false
//              return
//            }
//            // 上传题目图片
//            const formData = new FormData()
//            optionImages.forEach(file => {
//              formData.append('file', file)
//            })
//            const { code, data } = await imageService.uploadVideo(formData) || {}
//            if (code !== 200) {
//              this.$message.info(`第${i + 1}行图片上传失败`)
//              this.loading = false
//              return
//            }
//            const { fileName, fileUrl } = data
//            questionOptionList[i].imageName = fileName
//            questionOptionList[i].imageUrl = fileUrl
//          }
//        }
//      }
      const params = {
        question: {
          analysis,
          imageName,
          imageUrl,
          questionType,
          questionScore,
          questionTitle,
          questionTypeSel,
          questionAnswer,
          ...addCommonInfo,
          questionAnswerReply: questionTypeSel === 3 ? questionAnswerReply : ''
        },
        examList: examIds.split(',').filter(f => f).map(m => ({ id: m })),
        questionOptionList: questionOptionList.map(({ key, ...m }) => ({ ...m, ...addCommonInfo }))
      }
      const { code, msg } = await questionService.saveOrUpdate(params) || {}
      this.loading = false
      if (code !== 200) {
        this.$message.error(msg || '新增失败')
        return
      }
      this.$message.success('新增成功')
      this.resetFields()
      this.visible = false
      this.$emit('ok')
    },
    async edit () {
      let { imageName, imageUrl } = this.postForm
      const { id, questionTypeSel, questionType, examIds, questionTitle } = this.postForm
      const { questionAnswer, questionAnswerReply, questionScore, analysis, questionOptionList } = this.postForm
      // 验证客观题选项内容不能为空
      for (let i = 0; i < questionOptionList.length; i += 1) {
        if (!questionOptionList[i].content.trim()) {
          this.$message.info(`第${i + 1}行答案内容不能为空`)
          return
        }
      }
      // 验证主观题答案不能为空
      if (questionTypeSel === 3 && !questionAnswerReply) {
        this.$message.info('主观题答案不能为空')
        return
      }
      this.loading = true
      // 验证题目是否上传了图片
//      const questionImages = this.$refs.questionImage.getFileList()
//      const _questionImages = questionImages.filter(f => f instanceof File)
//      if (id && _questionImages.length > 0) {
//        // 题目图片类型、大小验证
//        const { flag, msg_ } = validateRules.validateImgTypeAndSize(_questionImages)
//        if (!flag) {
//          this.$message.info(msg_)
//          this.loading = false
//          return
//        }
//        // 上传题目图片
//        const formData = new FormData()
//        _questionImages.forEach(file => {
//          formData.append('file', file)
//        })
//        const { code, data, msg } = await imageService.uploadVideo(formData) || {}
//        if (code !== 200) {
//          this.$message.error(msg || '上传题目图片失败')
//          this.loading = false
//          return
//        }
//        const { fileName, fileUrl } = data
//        imageName = fileName
//        imageUrl = fileUrl
//      }
//      if (questionOptionList.length > 0) {
//        // 验证题目选项是否上传了图片
//        for (let i = 0; i < questionOptionList.length; i += 1) {
//          const optionImages = this.$refs['optionImage' + i].getFileList()
//          const _optionImages = optionImages.filter(f => f instanceof File)
//          if (questionOptionList[i].id && _optionImages.length > 0) {
//            // 题目图片类型、大小验证
//            const { flag, msg_ } = validateRules.validateImgTypeAndSize(_optionImages)
//            if (!flag) {
//              this.$message.info(msg_)
//              this.loading = false
//              return
//            }
//            // 上传题目图片
//            const formData = new FormData()
//            _optionImages.forEach(file => {
//              formData.append('file', file)
//            })
//            const { code, data } = await imageService.uploadVideo(formData) || {}
//            if (code !== 200) {
//              this.$message.info(`第${i + 1}行图片上传失败`)
//              this.loading = false
//              return
//            }
//            const { fileName, fileUrl } = data
//            questionOptionList[i].imageName = fileName
//            questionOptionList[i].imageUrl = fileUrl
//          }
//        }
//      }
      if(typeof examIds == 'object') {
          var examList = [{id:examIds[0]}]
      }else {
        var examList = examIds.split(',').filter(f => f).map(m => ({ id: m }))
      }
      const params = {
        question: {
          id,
          analysis,
          imageName,
          imageUrl,
          questionType,
          questionScore,
          questionTitle,
          questionTypeSel,
          questionAnswer,
          ...editCommonInfo,
          questionAnswerReply: questionTypeSel === 3 ? questionAnswerReply : ''
        },
        examList: examList,
        questionOptionList: questionOptionList.map(({ key, ...m }) => ({ ...m, ...editCommonInfo }))
      }
      const { code, msg } = await questionService.saveOrUpdate(params) || {}
      this.loading = false
      if (code !== 200) {
        this.$message.error(msg || '修改失败')
        return
      }
      this.$message.success('修改成功')
      this.resetFields()
      this.visible = false
      this.$emit('ok')
    },
    handleSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return false
        if (this.mode === 'add') {
          this.save()
        }
        if (this.mode === 'edit') {
          this.edit()
        }
      })
    },
    resetFields () {
      this.postForm = {
        id: '',
        questionTypeSel: '',
        questionType: 0,
        examIds: undefined,
        questionTitle: '',
        imageName: '',
        imageUrl: '',
        questionAnswer: '',
        questionAnswerReply: '',
        questionScore: 1,
        analysis: '',
        questionOptionList: [] // 题目选项
      }
      // 清除题目图片
//      this.$refs.questionImage.clearFileList()
      this.resetForm()
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
   .filter-container {
     .filter-item {
       display: inline-block;
       vertical-align: middle;
       margin-bottom: 10px;
     }
   }
   /deep/.ant-form-item {
     margin-bottom: 12px;
   }
  /deep/.ant-form-item-label {
    width: 100px;
  }
  /deep/.ant-table-tbody > tr > td {
    padding: 5px;
  }
  /deep/.ant-upload-picture-card-wrapper {
    width: 58px;
  }
  /deep/form .ant-mentions, form textarea.ant-input {
    height: auto;
    margin-bottom: -2px;
  }
  /deep/.ant-empty-normal {
    margin: 0;
  }
  /deep/.ant-table-placeholder {
    padding: 8px;
  }
</style>
